import json

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE


class CartsView(View):
    def post(self, request):
        # 1.接收非表单 -json参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 2.校验
        # 2.1 判断sku是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('商品不存在')
        # 2.2 判整
        try:
            count = int(count)
        except:
            return http.HttpResponseForbidden('count不是整型')
        # 2.3 判断是否是bool
        if selected:
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden('selected不是布尔类型')
        # 3.判断是否登录
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        if user.is_authenticated:
            # 3.1 登录--redis存储
            # 3.2 链接数据库
            reids_carts_client = get_redis_connection('carts')
            # 3.3 查询该用户的 所有购物车数据
            client_data = reids_carts_client.hgetall(user.id)

            # 3.4 判断是否有：
            if str(sku_id).encode() in client_data:
                # 有count+=1
                bytes_carts = client_data[str(sku_id).encode()]
                str_carts = bytes_carts.decode()
                dict_carts = json.loads(str_carts)

                # carts_data = json.loads(client_data[str(sku_id).encode()].decode())

                dict_carts['count'] += count
                reids_carts_client.hset(user.id, sku_id, json.dumps(dict_carts))
            else:
                # 没有 直接新增
                reids_carts_client.hset(user.id, sku_id, json.dumps({"count": count, "selected": selected}))

        else:
            # 3.2 未登录---cookie存储
            cooike_str = request.COOKIES.get('carts')
            # 3.2.1 获取cookie中所有的购物车数据
            if cooike_str:
                carts_dict = CookieSecret.loads(cooike_str)
            else:
                carts_dict = {}
            # 3.2.2 解密
            if sku_id in carts_dict:
                origin_count = carts_dict[sku_id]['count']
                count += origin_count
            # 3.2.3 判断是否存在
            # 存在 累加
            # 不存在 新增

            carts_dict[sku_id] = {'count': count, 'selected': selected}
            # 3.2.4 加密
            dumps_str = CookieSecret.dumps(carts_dict)

            # 重新插入cooike
            response.set_cookie('carts', dumps_str, max_age=14*24*3600)
        # 4.返回响应
        return response

    def get(self, requset):
        # 1.判断是否登录
        user = requset.user
        if user.is_authenticated:
            # 登录 --获取数据--redis
            # 1.链接
            client = get_redis_connection('carts')
            # 2.hgetall
            carts_redis = client.hgetall(user.id)
            carts_dict = {}
            for key, value in carts_redis.items():
                cart_key = int(key.decode())
                carts_redis_dict = json.loads(value.decode())
                carts_dict[cart_key] = carts_redis_dict

            # carts_dict = {int(key.decode()): json.loads(value.decode()) for key, value in carts_redis.items()}
        else:
            # 没登录---cookie
            cookie_str = requset.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}

            # 获取所有的商品的sku_ids
            # sku_ids ==== skus
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
                cart_skus.append({
                    'id': sku.id,
                    'name': sku.name,
                    'count': carts_dict[sku.id]['count'],
                    'selected': str(carts_dict[sku.id]['selected']),  # 将True，转'True'，方便json解析
                    'default_image_url': sku.default_image.url,
                    'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                    'amount': str(sku.price * carts_dict[sku.id]['count']),

                })
        context = {
            'cart_skus': cart_skus,
        }
        return render(requset, 'cart.html', context)

    def put(self, request):
        # 接收和校验参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')

        # 判断count是否为数字，整数
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected 是否是boolean值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        # 接收cookie最后的数据
        cookie_cart_str = ""
        if user.is_authenticated:
            # 1.链接redis
            carts_redis_client = get_redis_connection('carts')
            # 2.覆盖redis以前的数据
            new_data = {'count': count, 'selected': selected}
            carts_redis_client.hset(user.id, sku_id, json.dumps(new_data))
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转化成bytes,再将bytes转成base64的bytes,最后将bytes转成字典
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            # 覆盖以前的数据
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 转化承密文数据
            cookie_cart_str = CookieSecret.dumps(cart_dict)

        # 构建前端的数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }

        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})

        if not user.is_authenticated:
            # 相应结果并将购物车数据写入导cookie
            response.set_cookie('carts', cookie_cart_str, max_age=14*24*3600)

        return response

    def delete(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 2.校验
        # 判断sku_id是否cunas
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户登录，删除reids购物车
            cart_redis_client = get_redis_connection("carts")
            # 根据用户的id删除商品sku
            cart_redis_client.hdel(user.id, sku_id)

            # 删除结束后，没有响应的数据，只需要相应状态码即可
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 转化成明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            # 创建相应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转化为密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 相应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=24 * 14 * 3600)

            return response


class CartsSelectAllView(View):
    def put(self, requset):
        # 接收参数校验参数
        json_dict = json.loads(requset.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        # 判断用户是否登录
        user = requset.user
        if user.is_authenticated:
            # 用户已经登录，操作redis
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)

            # 将所有商品的 选中状态进行修改
            for key, value in carts_data.items():
                sku_id = int(key.decode())
                carts_dict = json.loads(value.decode())

                # 修改所有商品的选中状态
                carts_dict['selected'] = selected
                # 修改结果添加到数据库
                carts_redis_client.hset(user.id, sku_id, json.dumps(carts_dict))

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            carts_str = requset.COOKIES.get('carts')
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})

            if carts_str is not None:
                cart_dict = CookieSecret.loads(carts_str)
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
                cookie_cart = CookieSecret.dumps(cart_dict)
                response.set_cookie('carts', cookie_cart, max_age= 14 * 24 * 3600)
            return response


class CartsSimpleView(View):
    def get(self, request):
        # 判断登录

        if request.user.is_authenticated:
            # redis-取所有
            redis_client = get_redis_connection('carts')
            # 数据
            carts_data = redis_client.hgetall(request.user.id)
            # bytes---str dict
            # carts_dict = {}
            # for key,value in carts_data.items():
            #     sku_key = int(key.decode())
            #     sku_value = json.loads(value.decode())
            #     carts_dict[sku_key] = sku_value
            carts_dict = {int(key.decode()): json.loads(value.decode()) for key, value in carts_data.items()}

        else:
            cookies_str = request.COOKIES.get('carts')

            if cookies_str:
                # cookie---
                carts_dict = CookieSecret.loads(cookies_str)
            else:
                carts_dict = {}
        skus = SKU.objects.filter(id__in=carts_dict.keys())
        skus_list = []
        # 构建前端的数据格式
        for sku in skus:
            skus_list.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url,
            })
        # 返回前端
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': skus_list})
